package com.cabal.aliyun;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dypnsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dypnsapi20170525.models.SendSmsVerifyCodeRequest;
import com.aliyun.sdk.service.dypnsapi20170525.models.SendSmsVerifyCodeResponse;
import com.cabal.common.util.CabalJsonUtil;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CompletableFuture;

@Slf4j
public class AliyunSmsUtil {

    //@Value("${aliyun.sms.accessKeyId:LTAI5tJ1LHJBbigfiLXUGxv5}")
    private static String accessKeyId = "LTAI5tN1SLtfaF9dnG9ULeYJ";

    //@Value("${aliyun.sms.accessKeySecret:b0oBuUCWW3Ayibnzvxdv00DWROKvU0}")
    private static String accessKeySecret = "LZG0xTucUJruY8E4ZZwrLVSzq90Fn5";

    //@Value("${aliyun.sms.signName:skcabal}")
    //private static String signName = "贵州河佳运输有限公司";

    //@Value("${aliyun.sms.templateCode:SMS_288185809}")
    private static String templateCode = "SMS_490010410";

    /*public static String sendMessage(String targetPhone, String signName) {
        Client aliyunClient = null;
        try {
            aliyunClient = AliyunClient.createClient(accessKeyId, accessKeySecret);
        } catch (Exception e) {

        }

        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        String verifyCode = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        JSONObject codeJsonObject = new JSONObject();
        codeJsonObject.put("code", verifyCode);
        sendSmsRequest.setPhoneNumbers(targetPhone);
        sendSmsRequest.setSignName(signName);
        sendSmsRequest.setTemplateCode(templateCode);
        sendSmsRequest.setTemplateParam(codeJsonObject.toJSONString());
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = aliyunClient.sendSmsWithOptions(sendSmsRequest, runtime);
            log.info("短信发送返回参数>>>>{}", CabalJsonUtil.obj2json(sendSmsResponse));
            if(sendSmsResponse.getBody() == null || StringUtils.isBlank(sendSmsResponse.getBody().getCode())) {
                log.error("短信发送失败{}", sendSmsResponse.getBody().getMessage());
                verifyCode = "";
            }
        } catch (TeaException error) {
            verifyCode = "";
            log.error("TeaException：", error);
        } catch (Exception _error) {
            verifyCode = "";
            log.error("阿里云发送短信出错：", _error.getMessage());
        }
        return verifyCode;
    }*/

    public static String sendSmsVerifyCode(String targetPhone) {
        String verifyCode = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        try {
            StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                    .accessKeyId(accessKeyId)
                    .accessKeySecret(accessKeySecret)
                    .build());

            AsyncClient client = AsyncClient.builder()
                    .region("cn-shenzhen") // Region ID
                    .credentialsProvider(provider)
                    .overrideConfiguration(ClientOverrideConfiguration.create().setEndpointOverride("dypnsapi.aliyuncs.com"))
                    .build();


            AliyunSmsTemplateParam aliyunSmsTemplateParam = new AliyunSmsTemplateParam();
            aliyunSmsTemplateParam.setCode(verifyCode);
            aliyunSmsTemplateParam.setMin("5");
            SendSmsVerifyCodeRequest sendSmsVerifyCodeRequest = SendSmsVerifyCodeRequest.builder()
                    .phoneNumber(targetPhone)
                    .templateCode("100001")
                    .templateParam(CabalJsonUtil.obj2json(aliyunSmsTemplateParam))
                    .signName("速通互联验证码")
                    .build();

            CompletableFuture<SendSmsVerifyCodeResponse> response = client.sendSmsVerifyCode(sendSmsVerifyCodeRequest);
            SendSmsVerifyCodeResponse resp = response.get();
            System.out.println(new Gson().toJson(resp));
            // Finally, close the client
            client.close();
        } catch (Exception e) {
            log.error("阿里云短信认证发送错误", e);
        }

        return verifyCode;
    }


    public static void main(String[] args) {
        //AliyunSmsUtil.sendMessage("13632923376", "贵州河佳运输有限公司");
        //AliyunSmsUtil.sendMessage("13632923276", "");
        AliyunSmsUtil.sendSmsVerifyCode("18923805707");
    }
}
